package com.ruiysoft.controller.sms;

import com.alibaba.fastjson.JSON;
import com.ruiysoft.controller.sms.dto.GreetingDto;
import com.ruiysoft.controller.sms.service.GreetingApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * Created by 化增光 on 2019/2/22.
 */
@Controller
public class WebSocketController {

    private static final Logger log = LoggerFactory.getLogger(WebSocketController.class);

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Resource
    GreetingApiService greetingApiService;

    @MessageMapping("/message")
    //@SendToUser(value = "/greeting",broadcast = false)
    //客户端接收一对一消息的主题应该是“/user/” + 客户Id+分隔符+客服Id + “/greeting”
    public void message(GreetingDto message) throws Exception{
        System.out.println("进入后台！"+message.getContent());
        //通过convertAndSendToUser 向用户发送信息,
        message.setTime(System.currentTimeMillis());
        // 第一个参数是接收消息的用户,第二个参数是浏览器订阅的地址,第三个参数是消息本身
        messagingTemplate.convertAndSendToUser(message.getPrefix(),"/greeting", JSON.toJSONString(message));

        //System.out.println("后台调用:"+message.getMessage());
        //业务操作
        //记录聊天信息
        greetingApiService.addGreetings(message.getShopId(),message.getCustomer(),message.getCustomerService());
        greetingApiService.addMessage(message.getShopId(),message.getCustomer(),message.getCustomerService(),message);
    }
}
